#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from module_interfaces import CLI
from utils.log import logger


class TestSuite(CLI):
    def configure(self, parser):
        logger.debug("Test Suite configure")
        self.support_cmds = ['run', 'fetch', 'uninstall', 'install']
        for sub in self.support_cmds:
            subcommand = parser.choices.get(sub, None)
            if subcommand:
                subcommand.add_argument(
                    'test-suite', nargs="*", help='test suite names')
                subcommand.add_argument('--list', help='test suite list name')
                subcommand.add_argument(
                    '--verbose',
                    action="store_true",
                    help='show command execution output')
                subcommand.add_argument(
                    '--quite',
                    action="store_true",
                    help='show command execution output')

    def run(self, config):
        logger.debug("Test Suite run for parser result")
        if config.parser and config.parser['subcommand'] in self.support_cmds:
            if config.parser['quite']:
                config.is_quiet = True
            else:
                config.is_quiet = False

        if config.parser.get('list'):
            if config.test_list_path is None or config.test_list_path == '':
                config.test_list_path = os.getcwd()
            listfile = os.path.join(
                config.test_list_path, config.parser['list'])
            # TODO parse list file to test-suite
            with open(listfile, 'r') as fh:
                for line in fh:
                    test = line.strip()
                    if test.startswith('#'):
                        continue
                    config.test_list.append(test)
            if config.parser.get('test-suite', None):
                config.test_list.extend(list(set(config.parser['test-suite'])))

        elif config.parser.get('test-suite'):
            if isinstance(config.parser['test-suite'], str):
                config.parser['test-suite'] = [config.parser['test-suite']]
            for t in config.parser['test-suite']:
                config.test_list.append(t)
